package uk.co.nazz.f21mc_a2.utils;

import uk.co.nazz.f21mc_a2.DiaryApplication;
import uk.co.nazz.f21mc_a2.R;
import android.app.ListActivity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CalendarContract.Events;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;

public class EventsListLoader extends ListActivity implements
		LoaderManager.LoaderCallbacks<Cursor> {

	private DiaryApplication application;
	private String[] projection;
	private String selection;
	private String[] selectArgs;
	private String sortOrder;

	// This is the Adapter being used to display the list's data
	SimpleCursorAdapter cursorAdapter;

	// Grab the event data
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		application = (DiaryApplication) this.getApplication();

		// Create a progress bar to display while the list loads
		ProgressBar progressBar = new ProgressBar(this);
		progressBar.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
		progressBar.setIndeterminate(true);

		getListView().setEmptyView(progressBar);

		// Must add the progress bar to the root of the layout
		ViewGroup root = (ViewGroup) findViewById(R.id.events_list_listview_rootlayout);

		root.addView(progressBar);

		// For the cursor adapter, specify which columns go into which views
		String[] fromColumns = { Events.TITLE, Events.DTSTART, Events.DTEND };
		int[] toViews = { R.id.event_item_textview };

		// Create an empty adapter we will use to display the loaded data.
		// We pass null for the cursor, then update it in onLoadFinished()
		cursorAdapter = new SimpleCursorAdapter(this,
				R.layout.events_list_item, null, fromColumns, toViews, 0);
		setListAdapter(cursorAdapter);

		int calId = application.getDiary().getDiaryId();

		projection = new String[] { Events._ID, Events.TITLE };
		// This is the select criteria
		selection = "(" + Events.CALENDAR_ID + " =? )";
		selectArgs = new String[] { Integer.toString(calId) };
		// sort order
		sortOrder = Events.DTSTART + " DESC";

		getLoaderManager().initLoader(0, null, this);

	}

	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		return new CursorLoader(this, Events.CONTENT_URI,
				projection, selection, selectArgs, sortOrder);
	}


	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		cursorAdapter.swapCursor(data);
	}

	public void onLoaderReset(Loader<Cursor> loader) {
		cursorAdapter.swapCursor(null);
	}

}